package com.hdoit.apollo.logical.inStock.service.impl;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.druid.util.StringUtils;
import com.hdoit.apollo.logical.cargo.model.Collocation;
import com.hdoit.apollo.logical.cargo.service.ICollocationService;
import com.hdoit.apollo.logical.common.enums.purchase.PurchaseState;
import com.hdoit.apollo.logical.common.enums.stock.InStockType;
import com.hdoit.apollo.logical.inStock.dao.IInStockDao;
import com.hdoit.apollo.logical.inStock.model.InStock;
import com.hdoit.apollo.logical.inStock.model.InStockCollocation;
import com.hdoit.apollo.logical.inStock.model.InStockShow;
import com.hdoit.apollo.logical.inStock.service.IInStockCollocationService;
import com.hdoit.apollo.logical.inStock.service.IInStockService;
import com.hdoit.apollo.logical.inStock.service.IInStockShowService;
import com.hdoit.apollo.logical.purchase.model.Purchase;
import com.hdoit.apollo.logical.purchase.model.PurchaseCollocation;
import com.hdoit.apollo.logical.purchase.service.IPurchaseCollocationService;
import com.hdoit.apollo.logical.purchase.service.IPurchaseService;
import com.hdoit.apollo.logical.stock.model.Stock;
import com.hdoit.apollo.logical.stock.model.StockCollocation;
import com.hdoit.apollo.logical.stock.service.IStockCollocationService;
import com.hdoit.apollo.logical.stock.service.IStockService;
import com.hdoit.apollo.logical.viewmodel.stock.InStockSearch;
import com.tennetcn.core.common.enums.pub.YesOrNoInteger;
import com.tennetcn.core.common.utils.CommonUtils;
import com.tennetcn.core.common.utils.DateUtils;
import com.tennetcn.data.dao.base.impl.SuperService;
import com.tennetcn.data.enums.ModelStatus;
import com.tennetcn.data.message.PagerModel;
/**
 * @author      tancongzhu
 * @email       
 * @createtime  2018年04月02日 11:48:00
 * @comment
 */
@Component
public class InStockServiceImpl extends SuperService<InStock> implements IInStockService{

	@Autowired
	private IInStockShowService inStockShowService;
	@Autowired
	private IInStockCollocationService inStockCollocationService;
	@Autowired
	private IStockService stockService;
	@Autowired
	private IStockCollocationService stockCollocationService;
	@Autowired
	private IInStockDao inStockDao;
	@Autowired
	private ICollocationService collocationService;
	@Autowired
	private IPurchaseCollocationService purchaseCollocationService;
	@Autowired
	private IInStockService inStockService;
	
	@Autowired
	private IPurchaseService purchaseService;
	
	@Override
	public boolean applyInStock(InStock inStock, List<InStockShow> inStockShows) {
		List<InStockCollocation> inStockCollocations = new ArrayList<InStockCollocation>();
		if(super.applyChange(inStock)){
			if(inStock.getModelStatus() == ModelStatus.add){
				for (InStockShow inStockShow : inStockShows) {
					if (StringUtils.isEmpty(inStockShow.getShowId())) {
						inStockShow.setShowId(CommonUtils.getKeyId());
					}
					inStockShow.setInStockId(inStock.getInStockId());
					inStockShow.setModelStatus(ModelStatus.add);
					
					Stock stock=stockService.queryModelByKey(inStockShow.getCargoId());
					if( stock!= null){
						stock.setModelStatus(ModelStatus.update);
						
						stock.setStockNum(stock.getStockNum() + inStockShow.getInStockShowNum());
						stockService.applyChange(stock);
					}
					List<StockCollocation> stockCollocations = new ArrayList<StockCollocation>();
					for (InStockCollocation inStockCollocation : inStockShow.getInStockCollocations()) {
						if (StringUtils.isEmpty(inStockCollocation.getInStockCollocationId())) {
							inStockCollocation.setInStockCollocationId(CommonUtils.getKeyId());
						}
						inStockCollocation.setModelStatus(ModelStatus.add);
						inStockCollocations.add(inStockCollocation);
						
						for(StockCollocation stockCollocation:stock.getStockCollocations()) {
							if(stockCollocation.getCollocationId().equals(inStockCollocation.getCollocationId())) {
								stockCollocation.setModelStatus(ModelStatus.update);
								stockCollocation.setCollocationNum(stockCollocation.getCollocationNum()+inStockCollocation.getCollocationNum());
								stockCollocations.add(stockCollocation);
							}
						}
					}
					stockCollocationService.applyChanges(stockCollocations);
				}

			}else{
				for (InStockShow inStockShow : inStockShows) {
					inStockShow.setModelStatus(ModelStatus.update);
					for (InStockCollocation inStockCollocation : inStockShow.getInStockCollocations()) {
						inStockCollocation.setModelStatus(ModelStatus.update);
						inStockCollocations.add(inStockCollocation);
					}
				}

			}

			return inStockShowService.applyChanges(inStockShows)&&inStockCollocationService.applyChanges(inStockCollocations);
		}
		return false;
	}

	@Override
	public InStock queryModelById(String key) {
		return inStockDao.queryModelById(key);
	}

	@Override
	public boolean applyInStockForPC(InStock inStock,String ids) {
		boolean result=false;
		result=super.applyChange(inStock);
		System.err.println("主表"+result);
		if(result){
			if (inStock.getType().equals("1")) {
				result=applyBypurchase(inStock,ids);
			}
			
			if(result) {
				result=applyByInStockShow(inStock);
			}
		}else {
			throw new RuntimeException();
		}
		
		return result;
	}

	private boolean applyBypurchase(InStock inStock,String ids) {
		boolean result=false;
		String [] numMark=inStock.getInStockNums().split(",");
     	String [] collocationIds=inStock.getCollocationIds().split(",");
     	String [] pcIds=ids.split(",");
		Purchase purchase=new Purchase();
        List<PurchaseCollocation> purchaseCollocations=new ArrayList<PurchaseCollocation>();
        List<PurchaseCollocation> pcs=new ArrayList<PurchaseCollocation>();
        if(!StringUtils.isEmpty(inStock.getPurchaseId())){
        	purchase=purchaseService.queryModelByKey(inStock.getPurchaseId());
        	purchaseCollocations=purchaseCollocationService.queryListByPurchaseId(inStock.getPurchaseId());
        	purchase.setPurchaseInNum(purchase.getPurchaseInNum()+inStock.getInStockNum());
        }
      
        if (purchase.getPurchaseInNum().equals(purchase.getPurchaseNum())) {
        	purchase.setPurchaseState(PurchaseState.allIn);
        	
		}else if (purchase.getPurchaseInNum()<purchase.getPurchaseNum()&&purchase.getPurchaseInNum()>0) {
			purchase.setPurchaseState(PurchaseState.partIn);
		}
        
        purchase.setModifyDate(DateUtils.getCurrent());
        purchase.setModelStatus(ModelStatus.update);
       
        
        result=purchaseService.applyPurchase(purchase);
        if(result) {
        	 for (int i = 0; i < collocationIds.length; i++) {
     			for (PurchaseCollocation purchaseCollocation : purchaseCollocations) {
     				if (purchaseCollocation.getCollocationId().equals(collocationIds[i])&&purchaseCollocation.getId().equals(pcIds[i])) {
     					purchaseCollocation.setInStockNum(purchaseCollocation.getInStockNum()+Double.parseDouble(numMark[i]));
     					purchaseCollocation.setSurplusNum(purchaseCollocation.getSurplusNum()+Double.parseDouble(numMark[i]));
     					purchaseCollocation.setModifyDate(DateUtils.getCurrent());
     					purchaseCollocation.setModelStatus(ModelStatus.update);
     					pcs.add(purchaseCollocation);
     				}
     			}
     			
     		}
        	 result=purchaseCollocationService.applyChanges(purchaseCollocations);
        }else {
				throw new RuntimeException();
		}
        
        return result;
        
	}
	
	private boolean applyByInStockShow(InStock inStock) {
		boolean result=false;
		List<InStockShow> inStockShows=new ArrayList<InStockShow>();
		List<InStockShow> inStockShowsForAdd=new ArrayList<InStockShow>();
		if(inStock.getModelStatus() == ModelStatus.add){
			String [] collocationIds=inStock.getCollocationIds().split(",");
			String [] numStrings=inStock.getInStockNums().split(",");
			String [] units=inStock.getUnit().split(",");
			for (int i = 0; i < collocationIds.length; i++) {
				
				Double collocationNum=Double.parseDouble(numStrings[i]);
				//Collocation collocation=collocationService.queryModel(collocationIds[i]);
				Collocation collocation=collocationService.queryModelByCargo(collocationIds[i]);

				InStockShow inStockShow=new InStockShow();
				if (StringUtils.isEmpty(inStockShow.getShowId())) {
					inStockShow.setShowId(CommonUtils.getKeyId());
				}
				inStockShow.setCargoId(collocation.getCargoId());
				inStockShow.setInStockId(inStock.getInStockId());
				inStockShow.setShopId(inStock.getShopId());
				
				
				//单位换算,退货专用
				if (units[i].equals(collocation.getCargo().getUnit())) {
					inStockShow.setInStockShowNum(collocationNum);
				}else if (units[i].equals(collocation.getCargo().getViceFirstUnit())) {
					inStockShow.setInStockShowNum(collocationNum*collocation.getCargo().getFirstRatio());
				}else if (units[i].equals(collocation.getCargo().getViceSecondUnit())) {
					inStockShow.setInStockShowNum(collocationNum*collocation.getCargo().getSecondRatio());
				}
			
				inStockShow.setCreateDate(DateUtils.getCurrent());
				inStockShow.setDeleteMark(YesOrNoInteger.no);
				inStockShow.setModelStatus(ModelStatus.add);
				if (inStockShow.getInStockShowNum()>0) {
					inStockShows.add(inStockShow);
				}
				
			}
			HashMap<String, InStockShow> map=new HashMap<String, InStockShow>();
			
			for (InStockShow inStockShow : inStockShows) {
				String id=inStockShow.getCargoId();
				if (map.containsKey(id)) {
					Double number=map.get(id).getInStockShowNum();
					number+=inStockShow.getInStockShowNum();
					map.get(id).setInStockShowNum(number);
				}else {
					map.put(id, inStockShow);
					
				}
				
			}
			
			Iterator<Entry<String, InStockShow>> iter = map.entrySet().iterator();
			while (iter.hasNext()) {
				inStockShowsForAdd.add(iter.next().getValue());
			}
		}else {
			InStock inStocked=inStockService.queryModelById(inStock.getInStockId());
			for (InStockShow inStockShow : inStocked.getInStockShows()) {
				inStockCollocationService.deleteInStockCollocation(inStockShow.getShowId());
			}
			
			if(inStockShowService.deleteInStockShow(inStocked.getInStockId())) {
				System.err.println("茂"+result);
				String [] collocationIds=inStock.getCollocationIds().split(",");
				String [] numStrings=inStock.getInStockNums().split(",");
				String [] units=inStock.getUnit().split(",");
				
				//回退库存
				List<Stock> stocks = new ArrayList<Stock>();
				List<StockCollocation> stockCollocations = new ArrayList<StockCollocation>();
				for(InStockShow inStockShow:inStocked.getInStockShows()) {
					if(inStockShow.getInStockShowNum()!=0) {
						Stock stock=stockService.queryModelByKey(inStockShow.getCargoId());
						stock.setModelStatus(ModelStatus.update);
						for (InStockCollocation inStockCollocation : inStockShow.getInStockCollocations()) {
							for(StockCollocation stockCollocation:stock.getStockCollocations()) {
								if(stockCollocation.getCollocationId().equals(inStockCollocation.getCollocationId())) {
									stockCollocation.setCollocationNum(stockCollocation.getCollocationNum()+inStockCollocation.getCollocationNum()*inStockCollocation.getRatio());
									stockCollocation.setModelStatus(ModelStatus.update);
									stockCollocations.add(stockCollocation);
									stock.setStockNum(stock.getStockNum()+inStockCollocation.getCollocationNum()*inStockCollocation.getRatio());
									System.err.println(stock.getStockNum()+"cargo库存");
								}
							}
						}
						stocks.add(stock);
					}
				}
				result=stockService.applyChanges(stocks);
				if (result) {
					result=stockCollocationService.applyChanges(stockCollocations); 
				}
				//回退库存
				
				for (int i = 0; i < collocationIds.length; i++) {
					
					Double collocationNum=Double.parseDouble(numStrings[i]);
					//Collocation collocation=collocationService.queryModel(collocationIds[i]);
					Collocation collocation=collocationService.queryModelByCargo(collocationIds[i]);

					InStockShow inStockShow=new InStockShow();
					if (StringUtils.isEmpty(inStockShow.getShowId())) {
						inStockShow.setShowId(CommonUtils.getKeyId());
					}
					inStockShow.setCargoId(collocation.getCargoId());
					inStockShow.setInStockId(inStock.getInStockId());
					inStockShow.setShopId(inStock.getShopId());
					
					System.err.println("树"+result);
					//单位换算,退货专用
					if (units[i].equals(collocation.getCargo().getUnit())) {
						inStockShow.setInStockShowNum(collocationNum);
					}else if (units[i].equals(collocation.getCargo().getViceFirstUnit())) {
						inStockShow.setInStockShowNum(collocationNum*collocation.getCargo().getFirstRatio());
					}else if (units[i].equals(collocation.getCargo().getViceSecondUnit())) {
						inStockShow.setInStockShowNum(collocationNum*collocation.getCargo().getSecondRatio());
					}
				
					inStockShow.setCreateDate(inStocked.getCreateDate());
					inStockShow.setDeleteMark(YesOrNoInteger.no);
					inStockShow.setModelStatus(ModelStatus.add);
					if (inStockShow.getInStockShowNum()>0) {
						inStockShows.add(inStockShow);
						System.err.println("胡"+result);
					}
					
				}
				HashMap<String, InStockShow> map=new HashMap<String, InStockShow>();
				
				for (InStockShow inStockShow : inStockShows) {
					String id=inStockShow.getCargoId();
					if (map.containsKey(id)) {
						Double number=map.get(id).getInStockShowNum();
						number+=inStockShow.getInStockShowNum();
						map.get(id).setInStockShowNum(number);
					}else {
						map.put(id, inStockShow);
						
					}
					
				}
				
				Iterator<Entry<String, InStockShow>> iter = map.entrySet().iterator();
				while (iter.hasNext()) {
					inStockShowsForAdd.add(iter.next().getValue());
				}
			}
		}
		result=inStockShowService.applyChanges(inStockShowsForAdd);
		if(result) {
			System.err.println("我来了"+result);
			result=applyByInStockCollocation(inStock,inStockShowsForAdd);
		}else {
			throw new RuntimeException();
		}
		
		return result;
	}
	
	private boolean applyByInStockCollocation(InStock inStock,List<InStockShow> inStockShows) {
		boolean result=false;
		List<InStockCollocation> inStockCollocations = new ArrayList<InStockCollocation>();
		List<Stock> stocks=new ArrayList<Stock>();
		List<StockCollocation> stockCollocations = new ArrayList<StockCollocation>();
		String [] collocationIds=inStock.getCollocationIds().split(",");
		String [] numStrings=inStock.getInStockNums().split(",");
		String [] units=inStock.getUnit().split(",");
		
		for (InStockShow inStockShow : inStockShows) {
			Stock stock=stockService.queryModelByKey(inStockShow.getCargoId());
			if( stock!= null){
				stock.setModelStatus(ModelStatus.update);
				stock.setModifyDate(DateUtils.getCurrent());

				if (inStock.getType().equals(InStockType.outWarehouse)) {
					stock.setStockNum(stock.getStockNum() - inStockShow.getInStockShowNum());	
				} else if (inStock.getType().equals(InStockType.inWarehouse)) {
					stock.setStockNum(stock.getStockNum() + inStockShow.getInStockShowNum());
				}
				
				stocks.add(stock);
			}
			
			for (int j = 0; j < collocationIds.length; j++) {
				InStockCollocation inStockCollocation=new InStockCollocation();
				
				Collocation collocation=collocationService.queryModelByCargo(collocationIds[j]);
				//PurchaseCollocation purchaseCollocation=purchaseCollocationService.queryModelByCollocationId(collocationIds[j],inStock.getPurchaseId());
				if(inStockShow.getCargoId().equals(collocation.getCargoId())){
					if (StringUtils.isEmpty(inStockCollocation.getInStockCollocationId())) {
						inStockCollocation.setInStockCollocationId(CommonUtils.getKeyId());
						inStockCollocation.setCollocationId(collocationIds[j]);
						inStockCollocation.setCollocationNum(Double.parseDouble(numStrings[j]));
						inStockCollocation.setUnit(units[j]);
						if (units[j].equals(collocation.getCargo().getUnit())) {
							inStockCollocation.setRatio(1.0);
						}else if (units[j].equals(collocation.getCargo().getViceFirstUnit())) {
							inStockCollocation.setRatio(collocation.getCargo().getFirstRatio());							
						}else if (units[j].equals(collocation.getCargo().getViceSecondUnit())) {
							inStockCollocation.setRatio(collocation.getCargo().getSecondRatio());
						}						
						//采购退货价格，入库无价格
						if (!StringUtils.isEmpty(inStock.getInStockPrices())) {
							String[] priceForoutWarehouse=inStock.getInStockPrices().split(",");
							
							inStockCollocation.setRealPrice(Double.parseDouble(priceForoutWarehouse[j]));
						}
						
						inStockCollocation.setShowId(inStockShow.getShowId());
						inStockCollocation.setCreateDate(DateUtils.getCurrent());
						inStockCollocation.setShopId(inStock.getShopId());
						inStockCollocation.setDeleteMark(YesOrNoInteger.no);
						inStockCollocation.setModelStatus(ModelStatus.add);
						if (inStockCollocation.getCollocationNum()>0) {
							inStockCollocations.add(inStockCollocation);
						}
						
					}
				}
				
				
				for(StockCollocation stockCollocation:stock.getStockCollocations()) {
					if(stockCollocation.getCollocationId().equals(inStockCollocation.getCollocationId())) {
						System.err.println("修改库存");
						
						stockCollocation.setModifyDate(DateUtils.getCurrent());
						stockCollocation.setModelStatus(ModelStatus.update);
						
						if (inStock.getType().endsWith(InStockType.outWarehouse)) {
							stockCollocation.setCollocationNum(stockCollocation.getCollocationNum()-inStockCollocation.getCollocationNum()*inStockCollocation.getRatio());

						}else if (inStock.getType().endsWith(InStockType.inWarehouse)) {
							stockCollocation.setCollocationNum(stockCollocation.getCollocationNum()+inStockCollocation.getCollocationNum()*inStockCollocation.getRatio());
						}
						
						
						stockCollocations.add(stockCollocation);
					}
				}
			}
			
		}
		result=stockCollocationService.applyChanges(stockCollocations);
		System.err.println("通路0"+result);
		if(result) {
			System.err.println("通路1"+result);
			result=stockService.applyChanges(stocks);
			if(result) {
				result=inStockCollocationService.applyChanges(inStockCollocations);
				System.err.println("通路2"+result);
			}else {
				throw new RuntimeException();
			}
		}else {
			throw new RuntimeException();
		}
		return result;
	}
	
	@Override
	public List<InStock> queryInStockHistoryListByKey(String key) {
		
		return inStockDao.queryInStockHistoryListByKey(key);
	}

	@Override
	public InStock queryModelByKey(String key) {
		
		return inStockDao.queryModelByKey(key);
	}

	@Override
	public int queryCountMPForReturn(InStockSearch search) {
		
		return inStockDao.queryCountMPForReturn(search);
	}

	@Override
	public List<InStock> queryListMPForReturn(InStockSearch search,	PagerModel pagerModel) {
		
		return inStockDao.queryListMPForReturn(search,pagerModel);
	}

	@Override
	public InStock queryModelBySee(String key) {
		
		return inStockDao.queryModelBySee(key);
	}

	@Override
	public boolean closeInStock(InStock inStock, String loginId,String loginName) {
		
		inStock.setModifyDate(DateUtils.getCurrent());
		inStock.setModifyUserId(loginId);
		inStock.setModifyUserName(loginName);
		inStock.setModelStatus(ModelStatus.update);
		List<Stock> stocks = new ArrayList<Stock>();
		List<StockCollocation> stockCollocations = new ArrayList<StockCollocation>();
		for(InStockShow inStockShow:inStock.getInStockShows()) {
			if(inStockShow.getInStockShowNum()!=0) {
				Stock stock=stockService.queryModelByKey(inStockShow.getCargoId());
				
				
				stock.setModelStatus(ModelStatus.update);
				for (InStockCollocation inStockCollocation : inStockShow.getInStockCollocations()) {

					for(StockCollocation stockCollocation:stock.getStockCollocations()) {
						if(stockCollocation.getCollocationId().equals(inStockCollocation.getCollocationId())) {
							stockCollocation.setCollocationNum(stockCollocation.getCollocationNum()+inStockCollocation.getCollocationNum()*inStockCollocation.getRatio());
							stockCollocation.setModelStatus(ModelStatus.update);
							stockCollocations.add(stockCollocation);
							stock.setStockNum(stock.getStockNum()+inStockCollocation.getCollocationNum()*inStockCollocation.getRatio());
							System.err.println(stock.getStockNum()+"cargo库存");
						}
						
					}
				}
				stocks.add(stock);
			}
		}
		
		
		
		if(stocks != null && stocks.size() !=0 ){
			stockService.applyChanges(stocks);
		}
		if(stockCollocations != null && stockCollocations.size() !=0 ){
			stockCollocationService.applyChanges(stockCollocations);
		}
		return super.applyChange(inStock);
	}

	@Override
	public boolean deleteInStockByKey(String inStockId) {
		// TODO Auto-generated method stub
		return inStockDao.deleteInStockByKey(inStockId);
	}

}
